﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ArgGisUI
{
    public class ParallelSTAThreadTask
    {
        private List<Action<object>> tasks = new List<Action<object>>();
        ManualResetEvent manualResetEvent = new ManualResetEvent(false);
        public void AddTask(Action<object> task)
        {
            if (task == null)
                throw new ArgumentNullException("task");

            tasks.Add(task);
        }
        public void Start(object state)
        {            
            Thread importThread = new Thread(new ParameterizedThreadStart(this.StartMainThread));
            importThread.Start(state);            
        }
        private void StartMainThread(object state)
        {
            ManualResetEvent[] doneEvents = new ManualResetEvent[tasks.Count];
            for (int i = 0; i < tasks.Count; i++)
            {
                doneEvents[i] = new ManualResetEvent(false);
                Thread thread = new Thread(new ParameterizedThreadStart(this.StartChildTread));
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start(new STAThreadTaskInfo(tasks[i], doneEvents[i]));
            }
            WaitHandle.WaitAll(doneEvents);

            manualResetEvent.Set();
        }
        private void StartChildTread(object state)
        {
            STAThreadTaskInfo info = state as STAThreadTaskInfo;
            //执行方法
            info.task.Invoke(state);
            //完成
            info.ManualResetEvent.Set();
        }
        public void End()
        {
            manualResetEvent.WaitOne();
        }
    }
    public class STAThreadTaskInfo
    {
        public STAThreadTaskInfo(Action<object> task,ManualResetEvent resetEvent)
        {
            this.task = task;
            this.ManualResetEvent = resetEvent;
        }
        public Action<object> task;
        public ManualResetEvent ManualResetEvent;
    }
}
